import json
import logging
from datetime import datetime
import boto3

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    
    # Extract the posted fields from the message. 
    temperature = event['temperature']
    humidity = event['humidity']
    
    print(f"Temperature: {temperature}\nHumidity: {humidity}")
    logger.info(f"CloudWatch logs group: {context.log_group_name}")

    # Prepare a reply    
    Rtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
    dew_point = temperature - ((100 - humidity) / 5)
    reply = {"Timestamp": Rtime, "Temperature": temperature, "Dew point temperature": dew_point}  
    
    # Initialize the AWS IoT client
    iot_client = boto3.client("iot-data", region_name="us-east-2")

    topic = "data/actuator"
    payload = {
        "Timestamp": Rtime,
        "Temperature": temperature,
        "Dew point temperature": dew_point
    }
    
    response = iot_client.publish(
        topic=topic,
        qos=1,
        payload=json.dumps(payload)
    )
    
    return {
        "statusCode": 200,
        "body": json.dumps("Message published!")
    }

